package com.ych.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ych.beans.Alarm;
import com.ych.beans.Message;
import com.ych.dao.AlarmDao;
import com.ych.service.AlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AlarmServiceImpl implements AlarmService {
    @Autowired
    AlarmDao dao;
    @Autowired
    KafkaTemplate<String,String> kafkaTemp;

    @Override
    public Message addAlarm(Alarm alarm) {
        Message message = new Message();
        if (!dao.selectBySensorId(alarm.getSensor().getId())) {
            boolean isSuccess = dao.addAlarm(alarm);
            message.setSuccess(isSuccess);
            if (isSuccess) {
                kafkaTemp.send("alarm", JSON.toJSONString(alarm));
                message.setMsg("添加成功");
            } else {
                message.setMsg("添加失败");
            }
        }else {
            message.setSuccess(dao.updateAlarm(alarm));
            kafkaTemp.send("alarm", JSON.toJSONString(alarm));
        }
        return message;
    }

    @Override
    public Message selectAlarm(Integer pageNo, Boolean key, Date from, Date end) {
        if (pageNo != null){
            PageHelper.startPage(pageNo,8);
        }
        Message message = new Message();
        Integer selectKey = null;
        if (key != null) {
            selectKey = key ? 1 : 0;
        }
        List<Alarm> list = dao.selectAlarm(selectKey,from,end);
        if (!list.isEmpty()) {
            PageInfo<Alarm> pageInfo = new PageInfo<>(list);
            message.setObj(pageInfo);
        }
        message.setSuccess(true);
        return message;
    }

    @Override
    public Message updateAlarm(Alarm alarm) {
        Message message = new Message();
        boolean isSuccess = dao.updateAlarm(alarm);
        message.setSuccess(isSuccess);
        if (isSuccess){
            kafkaTemp.send("alarm", JSON.toJSONString(alarm));
            message.setMsg("修改成功");
        }else {
            message.setMsg("修改失败");
        }
        return message;
    }
}
